<template>
	<view class="">
<!-- 		<uni-nav-bar color="#333" @clickLeft="leftFun" :border="false" left-icon="left" backgroundColor="#fff"
			title="上传病例"></uni-nav-bar> -->

		<!--pages/upload/upload.wxml-->
		<view class="container">
			<view class="tips">
				{{titleTips}}
			</view>

			<view class="image-list-box">
				<view class="image-list" v-for="(item,index) in uploadedImageUrl" key="index">
					<image :src="item.fileUrl" mode=""></image>
					<uni-icons class="closeStyle" @click="close(item,index)" custom-prefix="custom-icon" type="clear"
						color="red" :size="26"></uni-icons>
				</view>
			</view>
			<view class='fixed b0 l0 w100 bg-color-white flex_l_m'>
				<view class="consultation-tip-box f28 c666" v-if="isConsultationTipShow" @click="onConsultation">
					<text>如果没有处方，点击这里<text class="color-primary" >到雀诊互联网医院问诊</text></text>
				</view>
				<view class='bg-color-white p30 pb40 flex_m'>
					<view class='operation-btn upload-btn flex_c_m ' @click='onChooseImage'>上传</view>
					<view class='operation-btn submit-btn flex_c_m ml30' @click="submitBtn">提交审核</view>
				</view>
			</view>
			<view>
				<!-- <van-overlay show="{{ isOverlayShow }}" bind:click="onClickOverlay">
		      <view class="image-detail-wrapper">
		        <image class="detail-image" src="{{detailImageUrl}}" mode="aspectFit" />
		      </view>
		    </van-overlay> -->
			</view>

		</view>
	</view>

</template>

<script>
	import {
		qzApi
	} from '@/config/request.js';
	export default {
		data() {
			return {
				uploadedImageUrl: [],
				uploadedImageList: [],
				ossSigned: {},
				orderId: '',
				isOverlayShow: false,
				detailImageUrl: '',
				isConsultationTipShow: false, // 是否显示去问诊tip
				selectedItemList: [],
				offlineItemList: [], // 强制纸质处方的药品
				onlineItemList: [], // 支持线上处方的药品
				otcItemList: [], // 无需处方的药品
				statustype:'',
				titleTips:""

			}
		},
		onLoad(e) {
			this.statustype=e.type;
			if(e.type==12){
				this.titleTips="请您务必上传已选药物的有效纸质处方。如有其他能辅助审核的病历资料也请一并上传（如诊断证明、出院小结等）"
			}else if(e.type==40){
				this.titleTips="请确保您上传的历史就诊资料能够证明您罹患某种疾病。这些资料将成为医生为您开具处方的关键依据。"
			}
			this.getOSSSigned(e.id)
			this.processFun(e.id)
			this.orderId = e.id;
			console.log(this.statustype,"111")
			console.log(this.orderId)
			if (e.itemList) {
				let list = JSON.parse(e.itemList)
				console.log(list)
				if (Array.isArray(list) && list.length > 0) {
					this.selectedItemList = list
				}
			}
			this.handleSelectedItemList()
		},
		onShow() {
			let data = uni.getStorageSync("describe1");
			if(data==2){
				uni.switchTab({
					url:"/pages/index/index"
				})
			}
		},
		methods: {
			onConsultation() {
				if (this.orderId) {
					uni.setStorageSync("describe1", 2)
				  uni.navigateTo({
				  	url: "/page1/consultationInfo/consultationInfo?orderId=" + this.orderId
				  })
				} else {
				  uni.showToast({
				    title: 'orderId为空',
				    icon: 'none'
				  })
				}
				
			},


			async submitBtn() {
				if (this.uploadedImageUrl.length <= 0) {
					uni.showToast({
						title: '您还没有上传病例',
						icon: "none",
						duration: 2000
					})
					return
				} else {
					uni.setStorageSync("describe1", 2)
					let form={
						orderId:this.orderId,
						type:this.statustype
					}
					const confirmData = await qzApi.confirmUploadFile(this.orderId,this.statustype)
					if (confirmData.code == 0) {
						uni.showModal({
							title: '',
							content: '您的处方已提交成功，请您耐心等待审核。\n大约1小时后，您可在“我的订单”中查找相应订单，审核通过后即可下单购药。',
							showCancel: false,
							success: (res) => {
								if (res.cancel) {
									// console.log('res.cancel', res.cancel);
								}								
								if (res.confirm) {
									// console.log('res.confirm', res.confirm);
									// this.gotoOrderList()
									uni.navigateTo({
										url: "/pages2/order/orderList"
									})

								}
							}
						})
					}
				}
			},
			async onChooseImage() {
				let that = this;
				uni.chooseImage({
					count: 9, // 可以选择的图片数量
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						for (var i = 0; i < tempFilePaths.length; i++) {
							// 将选定的图片添加到已上传图片列表
							var uploadedImage = tempFilePaths[i];
							that.uploadImageToOSS(uploadedImage)
						}
					}
				})
			},
			async uploadImageToOSS(filePath) {
				uni.showLoading({
					title:"上传中",
					mask:false,
				})
				this.uploadImgToOSSRequest(filePath, this.ossSigned, (resStr) => {
					const res = JSON.parse(resStr)
					console.log(res, "111");
					if (res && res.code == 0 && res.data) {
						uni.hideLoading()
						// uploadedImageUrl.value.push(res.data.fileUrl)
						this.uploadedImageUrl.push(res.data)
						this.$forceUpdate()
						console.log(this.uploadedImageUrl,"dskdk")

					} else if (res.code == -1) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					} else {
						uni.hideLoading()
					}
				})
			},


			// 删除图片
			async close(item, index) {
				let id=this.uploadedImageUrl[index].id
				
				this.uploadedImageUrl.splice(index, 1)
				const deleteData = await qzApi.deleteFile(id)

				if (deleteData.code == 0) {
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
					processFun(this.orderId)
				}

			},
			// 获取某个订单中已上传但未提交审核的病历
			async processFun(id) {
				const img = await qzApi.getFileOfOrder(id);
				this.uploadedImageUrl = img.data;

			},
			// 获取oss
			async getOSSSigned(id) {
				let form = {
					orderId: id,
					type:this.statustype
				}
				const getTradeId = await qzApi.getOSSSigned(form);

				this.ossSigned = getTradeId.data;
			},
			uploadImgToOSSRequest(filePath, ossSign, callBack) {
				console.log(filePath, "11");
				console.log(ossSign, "11222");
				let fileName = this.imageUUIDName(filePath.slice(9))
				console.log(fileName);
				let formData2 = {
					'key': ossSign.dir + fileName,
					'OSSAccessKeyId': ossSign.accessId,
					'policy': ossSign.policy,
					'Signature': ossSign.signature,
					'callback': ossSign.callback,
					'success_action_status': 200,
					'x-oss-forbid-overwrite': 'false'
				}
				uni.uploadFile({
					filePath: filePath,
					name: 'file',
					url: ossSign.host,
					formData: formData2,
					// header: {
					// 	'Content-Type': 'application/json'
					// },
					success(res) {
						const data = res.data
						console.log('success ', res)
						console.log(data)
						callBack(data);
					},
					fail(err) {
						console.log('err ', err)
						callBack(err);
					}
				})
			},
			getUUID() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			imageUUIDName(fileName) {
				let name = this.getUUID()
				if (fileName) {
					var list = fileName.split('.')
					name += '.'
					name += list[list.length - 1]
					// console.log(name)
				} else {
					name += '.jpeg'
				}
				return name
			},
			handleSelectedItemList() {

				let offlineItemList = []
				let onlineItemList = []
				let otcItemList = []
				this.selectedItemList.forEach(element => {
					if (element.rxType == 0 || element.rxType == '无需处方') {
						otcItemList.push(element)
					} else if (element.rxType == 1 || element.rxType == '支持线上处方') {
						onlineItemList.push(element)
					} else if (element.rxType == 2 || element.rxType == '强制纸质处方') {
						offlineItemList.push(element)
					}
				});


				this.offlineItemList = offlineItemList;
				this.onlineItemList = onlineItemList;
				this.otcItemList = otcItemList;

				this.handleIsConsultationTipShow()
			},
			handleIsConsultationTipShow() {
				console.log('handleIsConsultationTipShow');
				let flag
				if (this.onlineItemList.length > 0) {
					flag = true
				} else {
					flag = false
				}
				this.isConsultationTipShow = flag;
			}
		},

	}
</script>

<style scoped>
	/* pages/upload/upload.wxss */
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.tips {
		height: auto;
		padding: var(--notice-bar-wrapable-padding, 8px 16px);
		align-items: center;
		background-color: var(--notice-bar-background-color, #fffbe8);
		color: var(--notice-bar-text-color, #ed6a0c);
		display: flex;
		font-size: 28rpx;
	}

	.image-list-box {
		display: flex;
		padding: 20rpx;
		/* display: grid; */
		width: 100%;
		height: 100%;
		margin-bottom: 100rpx;
		flex-wrap: wrap;

		/* background-color: aqua; */
	}

	.image-list {
		width: 33.33%;
		position: relative;
		/* margin-bottom: 20rpx; */
		background: #ffffff;
		padding: 20rpx;
	}

	.image-list .closeStyle {
		position: absolute;
		right: 0rpx;
		top: 0;
	}

	.image-list image {
		width: 100%;
		height: 200rpx;
	}

	.image-list-grid {
		position: relative;
		width: 100%;
		height: 100%;
		/* background-color: blueviolet; */
	}

	.image-list-grid-item {
		background-color: #ffffff00;
	}

	.uploaded-image-container {
		/* padding: 20rpx; */
		position: relative;
		width: 100%;
		height: 100%;
		/* background-color: antiquewhite */
	}

	.uploaded-image {
		/* width: 25vw;
	  height: 25vw; */
		width: 100%;
		height: 100%;
	}

	.delete-icon-box {
		position: absolute;
		right: -10rpx;
		top: -20rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background-color: #ff0000;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.delete-button {
		/* background-color: #ff0000; */
		/* color: white; */
		/* border: none; */
		/* padding: 5px 10px; */
		/* border-radius: 50%; */
		/* margin-top: 5px; */
	}

	.upload-btn {
		background: var(--themeColor);
		border: 2rpx solid var(--themeColor);
		color: #fff;
	}

	.submit-btn {
		border: 2rpx solid var(--themeColor);
		color: var(--themeColor);
	}

	.operation-btn {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
	}

	.consultation-tip-box {
		padding: 20rpx;
	}

	.image-detail-wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.detail-image {
		width: 100%;
		height: 100%;
	}
</style>